package com.sise.aio和bio和nio.nio.nioServerClient;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 单线程版本 NioServer
 * @author idea
 * @createTime 2020-04-12
 */
public class NioServer {


    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.socket().bind(new InetSocketAddress(9090));
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            System.out.println("there is a new conn coming ");
            //轮训监听key信息
            selector.select();
            System.out.println("event happen");
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> selectionKeyIterator = selectionKeys.iterator();
            while (selectionKeyIterator.hasNext()) {
                SelectionKey selectionKey = selectionKeyIterator.next();
                //就是一个安全处理部分
                selectionKeyIterator.remove();
                handle(selectionKey);
            }
        }
    }


    /**
     * 处理多种事件
     *
     * @param selectionKey
     */
    public static void handle(SelectionKey selectionKey) throws IOException {
        if (selectionKey.isAcceptable()) {
            System.out.println("this is accept");
            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
            //nio非堵塞的关键之处，这里的accept是非堵塞的，但是当有链接来的时候这里就不会堵塞了，处理完链接之后就立马转向去处理下一个链接事件
            SocketChannel socketChannel = serverSocketChannel.accept();
            socketChannel.configureBlocking(false);
            socketChannel.register(selectionKey.selector(), SelectionKey.OP_READ);
        } else if (selectionKey.isReadable()) {
            System.out.println("this is read");
            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            //这里不会发生堵塞
            int len = socketChannel.read(byteBuffer);
            if (len != -1) {
                System.out.println("read msg is " + new String(byteBuffer.array(), 0, len));
            }

            ByteBuffer byteBuffer2write = ByteBuffer.wrap("hello client".getBytes());
            socketChannel.write(byteBuffer2write);
            //需要重新设置这个selectionKey关联的事件
            selectionKey.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
            socketChannel.close();
        }
    }


}
